package phone.qyg.com.qyg.utils;

import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.FieldInfo;
import phone.qyg.com.qyg.model.FieldPlace;
import phone.qyg.com.qyg.model.FieldPrice;
import phone.qyg.com.qyg.model.FitMap;
import phone.qyg.com.qyg.model.MapTheme;

/**
 * 作者：lblbh on 2017/3/17 11:28
 * 邮箱：lanbuhan@163.com
 * 功能：网络请求整体
 */
public class AppHttpRequest {

    /**
     * 用户信息获取
     * @param onAppHttpListener
     */
    public static void getUserInfo(final OnAppHttpListener onAppHttpListener){
        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.USER_MSG,
                null,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(true,result);
                        /**
                         "code": 100,
                         "flag": false,
                         "status": 1,
                         "statusText": "?????????token???????????"
                         */
                        if(!JSONTool.isStatus(result)){
                            if(result.contains("code")){
                                SharePrefUtil.saveString(SharePrefUtil.KEY.APP_USER,"");
                            }
                            return;
                        }
                        //考虑离线问题 默认做存储
                        SharePrefUtil.saveString(SharePrefUtil.KEY.APP_USER, JSONTool.requestJSONStringKey(result, JSONTool.Enum.DATA));
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(false,null);
                    }

                });
    }

    public static void getDiscussList(int id,int type,int page,final OnAppHttpListener onAppHttpListener){
        Map<String,String> kMap = new HashMap<String,String>();
        kMap.put(AppHttpKey.TYPE,String.valueOf(type));
        kMap.put(AppHttpKey.PAGE_NO,String.valueOf(page));
        kMap.put(AppHttpKey.OBJECT_ID,String.valueOf(id));
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.COMMENT_LIST,
                kMap,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(true,result);
                    }
                });
    }


    /**
     * 应用配置信息
     */
    public static void httpAppInfo(final OnAppHttpListener onAppHttpListener){
        httpRequestDefalut(ApplicationConfig.APP_INFO,
                null,
                new OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState && JSONTool.isStatus(result)){
                            SharePrefUtil.saveString(SharePrefUtil.KEY.APP_INFO,result);
                        }

                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(isState,result);
                    }
                });
    }

    /**
     * 添加/取消收藏
     * @param object_id
     * @param isCollection
     * @param type
     * @param title
     * @param onAppHttpListener
     */
    public static void collection(int object_id,int isCollection,String type,String title,final OnAppHttpListener onAppHttpListener){
        HashMap<String,String> mapKeys = new HashMap<String,String>();
        mapKeys.put(AppHttpKey.OBJECT_ID,String.valueOf(object_id));
        mapKeys.put(AppHttpKey.OPERATE_TYPE,String.valueOf((isCollection == 0)?0:1));
        mapKeys.put(AppHttpKey.TYPE,type);
        mapKeys.put(AppHttpKey.TITLE,title);

        /**
         *      “objectId”: 11   //收藏对象ID（场馆、活动、培训课程）（必填）
         “operateType”: 0      //0-收藏，1-取消收藏（必填）
         “type”:1 //收藏类型 0-场馆  1-活动  2:-培训课程（必填）
         “title”:”健身课程”    //收藏标题（收藏时填写）

         */
        //收藏
        AppHttpRequest.appQuitState(ApplicationConfig.COLLECTION_CONTENT,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(isState,result);
                    }
                });
    }

    /**
     * 添加视频学习进度
     * @param id
     * @param courseid
     * @param onAppHttpListener
     */
    public static void addCourseRecord(int id,String courseid,final OnAppHttpListener onAppHttpListener){
        HashMap<String,String> mapKeys = new HashMap<String,String>();
        mapKeys.put(AppHttpKey.ID,String.valueOf(id));
        mapKeys.put(AppHttpKey.COURSE_ID,courseid);
        mapKeys.put(AppHttpKey.TIME_LINE,"1000");

        /**
         “id”:1    //视频ID
         “course_id”:1 //课程Id
         “timeline”:100  //视频播放位置（秒）
         */
        //收藏
        AppHttpRequest.appQuitState(ApplicationConfig.ADD_COURSE_RECORD,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(isState,result);
                    }
                });
    }


    /**
     * 默认处理指请求方法
     * @param url
     * @param mapKey
     * @param onAppHttpListener
     */
    public static void httpRequestDefalut(String url, final Map<String,String> mapKey, final OnAppHttpListener onAppHttpListener){
        SystemPrintl.systemPrintl("-----url>"+url);
        Xutils.Get(ApplicationConfig.NET_DSN_PATH + url,
                mapKey,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(true,result);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(false,null);
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        if(mapKey != null && !mapKey.isEmpty())
                            mapKey.clear();
                    }
                });
    }

    /**
     * 默认post处理指请求方法
     * @param url
     * @param mapKey
     * @param onAppHttpListener
     */
    public static void httpPostRequestDefalut(String url, final Map<String,String> mapKey, final OnAppHttpListener onAppHttpListener){
        SystemPrintl.systemPrintl("-----url>"+url);
        Xutils.Post(ApplicationConfig.NET_DSN_PATH + url,
                mapKey,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(true,result);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        if(onAppHttpListener != null)
                            onAppHttpListener.onAppHttpState(false,null);
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        if(mapKey != null && !mapKey.isEmpty())
                            mapKey.clear();
                    }
                });
    }



    /**
     * 消息服务地址处理
     */
    public static void httpNoticeServiceHost(final OnAppInfoListener onAppInfoListener){

        Map<String,String> mapkeys = new HashMap<String,String>();
        String info = SharePrefUtil.getString(SharePrefUtil.KEY.APP_USER,null);
        if(CommonUtil.isRequestStr(info)){
            String token = JSONTool.requestJSONfindName(info, JSONTool.Enum.ACCESS_TOKEN);
            mapkeys.put("token",token);
        }

        Xutils.Get(ApplicationConfig.USER_NEW_MESS,
                mapkeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        SystemPrintl.systemPrintl("我在这里App_info---->>>"+result);
                        if(onAppInfoListener != null){
                            if(JSONTool.isStatus(result)){
                                int cnt = JSONTool.requestJSONfindNameCount(result, JSONTool.Enum.DATA, JSONTool.Enum.CNT);
                                onAppInfoListener.onAppInfo((cnt >0)?true:false,result);
                            }else{
                                onAppInfoListener.onAppInfo(false,result);
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        if(onAppInfoListener != null)
                            onAppInfoListener.onAppInfo(false,"");
                    }

                });
    }



    /**
     * 全局使用取消 接口统一 (全局 简单 返回成功/失败)
     * @param url
     * @param mapKey
     * @param onAppHttpListener
     */
    public static void appQuitState(String url, final Map<String,String> mapKey, final OnAppHttpListener onAppHttpListener){
        httpRequestDefalut(url,
                mapKey,
                new OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            //于服务器连接成功
                            if(JSONTool.isStatus(result)){
                                if(onAppHttpListener != null)
                                    onAppHttpListener.onAppHttpState(true,result);
                            }else{
                                //取消失败 统一处理
                                PromptManager.showToast(JSONTool.requestJSONfindName(result, JSONTool.Enum.STATUSTEXT));
                                if(onAppHttpListener != null)
                                    onAppHttpListener.onAppHttpState(false,result);
                            }
                        }else{
                            //于服务器连接失败--- 统一处理
                            PromptManager.showToast(R.string.service_error);
                        }
                    }
                });
    }

    /**
     * 全局使用取消 接口统一 (全局 简单 返回成功/失败)
     * @param url
     * @param mapKey
     * @param onAppHttpListener
     */
    public static void appQuitStatePost(String url, final Map<String,String> mapKey, final OnAppHttpListener onAppHttpListener){
        Xutils.Post(ApplicationConfig.NET_DSN_PATH + url,
                mapKey,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        //于服务器连接成功
                        if(JSONTool.isStatus(result)){
                            if(onAppHttpListener != null)
                                onAppHttpListener.onAppHttpState(true,result);
                        }else{
                            //取消失败 统一处理
                            PromptManager.showToast(JSONTool.requestJSONfindName(result, JSONTool.Enum.STATUSTEXT));
                            if(onAppHttpListener != null)
                                onAppHttpListener.onAppHttpState(false,result);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        //于服务器连接失败--- 统一处理
                        PromptManager.showToast(R.string.service_error);
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        if(mapKey != null && !mapKey.isEmpty())
                            mapKey.clear();
                    }
                });
    }

    public static void fitMapRequest(final OnFitmapRequestResult onFitmapRequestResult){
        httpRequestDefalut(ApplicationConfig.APP_FIT_MAP,
                null,
                new OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        List<MapTheme> themes = new ArrayList<MapTheme>();
                        if(isState){
                            List<FitMap> fitMaps = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.NEAR_BY_SERVICE, FitMap.class);
                            if(CommonUtil.isRequestList(fitMaps)){
                                for(int i=0,j=fitMaps.size();i<j;i++){
                                    //int id, String title, int type
                                    FitMap itemFitmap = fitMaps.get(i);
                                    MapTheme theme = new MapTheme(itemFitmap.id,itemFitmap.title,itemFitmap.type,itemFitmap.color,itemFitmap.imgUrl);
                                    themes.add(theme);
                                    themes.add(new MapTheme(0,"",itemFitmap.type));
                                    themes.add(new MapTheme(0,"",itemFitmap.type));
                                    themes.add(new MapTheme(0,"",itemFitmap.type));
                                    int itemContentSize = itemFitmap.content.size();
                                    int divide = itemContentSize % 4;
                                    if(divide != 0){
                                        for (int z=0,k=(4-divide);z<k;z++){
                                            themes.add(new MapTheme());
                                        }
                                    }
                                    themes.addAll(itemFitmap.content);
                                }
                            }
                        }
                        if(onFitmapRequestResult != null)
                            onFitmapRequestResult.onFitmapResult(themes);
                    }
                });
    }



    public static final String FIELD_INFO_PLACE = "field_place";
    public static final String FIELD_INFO_PRICE = "field_price";
    public static final String FIELD_INFO_TIME = "field_time";
    /**
     /**
     *  评论点赞
     */
    public static void getFieldMap(int roomId,int venueId,final OnFieldMapListener onFieldMapListener){
        final Map<String,Object> infoMap = new HashMap<String,Object>();
        /**
         * phone.nmty.com.nmty.model.FieldInfo
         * /Users/lblbh/Documents/workspace/androidstudio/nmty/app/src/main/java/phone/nmty/com/nmty/model/FieldInfo.java
         http://192.168.1.44:8080/mobi/venue/getpricebytime?sub_date=2017-04-13&item_id=36&code=4
         */

        Map<String,String> mapKey = new HashMap<String,String>();
        mapKey.put(AppHttpKey.ROOM_ID,String.valueOf(roomId));
        mapKey.put(AppHttpKey.VENUE_ID,String.valueOf(venueId));

        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.VENUE_INFO_ORDER,
                mapKey,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        FieldInfo fieldInfo = JSONTool.jsonDefaluTranClazz(result,null, FieldInfo.class);
                        if(fieldInfo != null){
                            //placeList

                            List<FieldPrice> timeList = fieldInfo.subTimeArray;
                            List<FieldPlace> places = fieldInfo.dateArray;
                            if(CommonUtil.isRequestList(places)){
                                //动态添加一条空数据 处理不显示
                                FieldPlace place = new FieldPlace();
                                place.week = " ";
                                place.sub_date = "";
                                place.date = "";
                                places.add(0,place);
                            }
                            infoMap.put(FIELD_INFO_PLACE,places);
                            infoMap.put(FIELD_INFO_TIME,timeList);
                            List<List<FieldPrice>> blockList = fieldInfo.dateSubtimeArray;

                            //最后结果集合
                            List<List<FieldPrice>> models = new ArrayList<List<FieldPrice>>();
                            for (int i=0,j=blockList.size();i<j;i++){
                                List<FieldPrice> prices = blockList.get(i);
                                //这个是时间对象
                                if(timeList.size() <= i){
                                    break;
                                }
                                FieldPrice price = timeList.get(i);
                                price.type = 1;
                                //将时间对象添加到集合第一个元素
                                prices.add(0,price);
                                models.add(prices);
                            }
                            infoMap.put(FIELD_INFO_PRICE,models);
                            if(onFieldMapListener != null)
                                onFieldMapListener.onFieldState(true,infoMap);
                        }else{
                            if(onFieldMapListener != null)
                                onFieldMapListener.onFieldState(false,null);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        if(onFieldMapListener != null)
                            onFieldMapListener.onFieldState(false,null);
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                    }
                });
    }



    public interface  OnAppHttpListener{
        public void onAppHttpState(boolean isState, String result);
    }

    public interface OnAppInfoListener{
        public void onAppInfo(boolean isNewInfo,String result);
    }

    public interface OnFitmapRequestResult{
        public void onFitmapResult(List<MapTheme> themes);
    }

    public interface OnFieldMapListener{
        public void onFieldState(boolean isState,Map<String,Object> infoMap);
    }
}
